<template>
	<view>
		<view v-if="loading" class="page-loading"><u-loading mode="circle"></u-loading></view>
		<!-- 主要内容 -->
		<view v-else class="page-main">
			<view class="grid-box">
				<view class="u-p-b-20 u-flex">
					<view class="u-flex-1">
						<view class="address">
							<text class="u-font-32 u-p-r-20">{{details.name}}{{ details.parentid > 0?'-'+details.department:'' }}</text>
							<text class="links" @click="edit"><u-icon name="edit-pen"></u-icon>修改</text>
						</view>
						<view class="u-p-t-8">
							<view class="u-flex u-font-24">
								<text class="u-font-24 u-tips-color">所属加盟商：{{details.franchise.name}}</text>
							</view>
						</view>
					</view>
				</view>
				
				<!-- <view class="bottom u-border-top u-p-t-20">
					<view>
						<text class="u-font-24 u-tips-color">绑定账户：{{details.user.name}}</text>
					</view>
					<view>
						<text class="u-font-24 u-tips-color">管理模式：{{details.financemode}}</text>
					</view>
					<view>
						<text class="u-font-24 u-tips-color">所属地区：{{details.city.citynames}}</text>
					</view>
				</view> -->
				
				<view class="middle u-border-top u-p-t-20 u-m-b-30">
					<view class="u-flex">
						<view class="item u-border-right" @click="changeMode">
							<text class="label u-tips-color">管理模式</text>
							<view class="u-m-t-8 u-m-b-8">
								<text class="u-flex-1 u-text-right u-font-32">{{details.financemode}}</text>
							</view>
							<text class="links"><u-icon name="edit-pen"></u-icon>更换模式</text>
						</view>
						<view class="item u-border-right" @click="unbinding" v-if="details.user">
							<text class="label u-tips-color">绑定账户</text>
							<view class="u-m-t-8 u-m-b-8">
								<text class="u-flex-1 u-text-right u-font-32">{{details.user.name}}</text>
							</view>
							<text class="links"><u-icon name="edit-pen"></u-icon>解绑</text>
						</view>
						<view class="item u-border-right" @click="binding" v-else>
							<text class="label u-tips-color">绑定账户</text>
							<view class="u-m-t-8 u-m-b-8">
								<text class="u-flex-1 u-text-right u-font-32">未绑定</text>
							</view>
							<text class="links"><u-icon name="edit-pen"></u-icon>绑定</text>
						</view>
						<view class="item" @click="cityshow = true">
							<text class="label u-tips-color">所属地区</text>
							<view class="u-m-t-8 u-m-b-8">
								<text class="u-flex-1 u-text-right u-font-32">{{details.city.cityname}}</text>
							</view>
							<text class="links"><u-icon name="edit-pen"></u-icon>修改地区</text>
						</view>
					</view>
				</view>
				<view class="middle u-p-t-20">
					<view class="u-flex">
						<view class="item u-border-right">
							<text class="label u-tips-color">账户余额</text>
							<view class="u-m-t-8 u-m-b-8">
								<text class="u-flex-1 u-text-right u-font-36">{{details.balance}}</text>
								<text class="unit">元</text>
							</view>
						</view>
						<view class="item u-border-right">
							<text class="label u-tips-color">累计提现</text>
							<view class="u-m-t-8 u-m-b-8">
								<text class="u-flex-1 u-text-right u-font-36">{{-details.cashout}}</text>
								<text class="unit">元</text>
							</view>
						</view>
						<view class="item">
							<text class="label u-tips-color">账户积分</text>
							<view class="u-m-t-8 u-m-b-8">
								<text class="u-flex-1 u-text-right u-font-36">{{details.integral}}</text>
								<text class="unit">分</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="u-tabs-box u-border-top">
				<u-tabs-swiper activeColor="#10beca" ref="tabs" :list="list" :current="current" @change="(index)=>{current = index}" :is-scroll="false" swiperWidth="750">
				</u-tabs-swiper>
			</view>
			
			<!-- 数据汇总 -->
			<view v-if="current == 0" class="u-border-top">
				<list-filter-panel ref="filterPanel" @filter-change="filterChange" @searchKeyword="searchKeyword"></list-filter-panel>
				<view class="u-p-l-30 u-p-r-30 u-p-t-10 u-p-b-10">
					<text class="u-font-24 u-tips-color">{{timeName}}数据汇总</text>
				</view>
				<view class="middle u-p-t-20 u-p-b-20 u-border-bottom">
					<view class="u-flex">
						<view class="item u-border-right">
							<text class="label u-tips-color">回收总重</text>
							<view class="u-m-t-8 u-m-b-8">
								<text class="u-flex-1 u-text-right u-font-36">{{originalTableData.weight}}</text>
								<text class="unit">KG</text>
							</view>
						</view>
						<view class="item u-border-right">
							<text class="label u-tips-color">回收单数</text>
							<view class="u-m-t-8 u-m-b-8">
								<text class="u-flex-1 u-text-right u-font-36">{{originalTableData.offlinecount+originalTableData.onlinecount}}</text>
								<text class="unit">单</text>
							</view>
						</view>
						<view class="item">
							<text class="label u-tips-color">回收总额</text>
							<view class="u-m-t-8 u-m-b-8">
								<text class="u-flex-1 u-text-right u-font-36">{{originalTableData.amount}}</text>
								<text class="unit">分</text>
							</view>
						</view>
					</view>
				</view>
				
				<view class="table-list">
					<view class="tr u-border-bottom">
						<view class="th"><text>类型</text></view>
						<view class="th u-text-left"><text>可回收物</text></view>
						<view class="th u-text-right"><text>数量(KG/件)</text></view>
						<view class="th u-text-right"><text>金额(元)</text></view>
					</view>
					<view v-for="(item,index) in tableData" :key="index">
						<view 
						class="tr"
						:class="index == tableData.length - 1?'last':'u-border-bottom'"
						@click="tableClick(item)"
						>
							<view class="td">
								<text>{{item.large}}</text>
							</view>
							<view class="td u-text-left">
								<text class="">{{item.name}}</text>
							</view>
							<view class="td u-text-right">
								<text class="u-font-bold">{{item.weight}}{{item.isweighing?'KG':'件'}}</text>
							</view>
							<view class="td u-text-right">
								<text class="u-font-bold">{{item.amount}}</text>
							</view>
						</view>
					</view>
					<!-- <view class="tr u-border-top">
						<view class="th"><text>合计</text></view>
						<view class="th u-text-left"><text>/</text></view>
						<view class="th u-text-right"><text>{{tableDataTotal.weight}}KG</text>,<text>{{tableDataTotal.quantity}}件</text></view>
						<view class="th u-text-right"><text>{{tableDataTotal.amount}}元</text></view>
					</view> -->
				</view>
				<view class="u-p-30" v-if="tableData.length == 0">
					<u-empty mode="data"></u-empty>
				</view>
			</view>
			<!-- 下级部门 -->
			<view v-if="current == 1" class="u-border-top">
				<enterpriseList :parentId="details.id"></enterpriseList>
			</view>
		</view>
		
		<!-- 选择所在地区 -->
		<citypicker ref="citypicker" :show="cityshow" :level="4" @select="getSelectCity" @close="cityshow = false"></citypicker>
		<!-- 选择客户列表 -->
		<customerList :show="showWindow" @close="showWindow = false" @confirm="bindUser"></customerList>
		<!-- 修改名称 -->
		<u-modal
			v-model="editDialogVisible" 
			:show-cancel-button="true" 
			:negative-top="200" 
			title="修改名称"
			@confirm="confirmEditName"
			>
			<scroll-view :scroll-y="true" class="slot-content">
				<view class="u-p-l-30 u-p-r-30 u-p-t-30">
					<u-form label-width="140rpx">
						<u-form-item label="" prop="reason">
							<u-input v-model="editname" type="text" :border="true" />
						</u-form-item>
					</u-form>
				</view>
			</scroll-view>
		</u-modal>
	</view>
</template>

<script>
	import staffList from '@/components/form-select-type/staff-list.vue'
	import customerList from '@/components/form-select-type/customer-list.vue'
	import enterpriseList from '@/pages/admin/franchise/enterprise/enterprise.vue'
	
	export default {
		components:{
			staffList,
			customerList,
			enterpriseList
		},
		data() {
			return {
				loading: true,
				details: {
					department: "",
					name: "",
					userId: '',
					mobile: '',
					id: '',
					enterprisename: '',
					cityId: 0
				},
				list: [
					{
						value: 0,
						name: '回收汇总'
					},
					{
						value: 1,
						name: '下级部门'
					}
				],
				current: 0,
				// 指定用户
				show: false,
				showWindow: false,
				addForm:{
					name: '',
					id: 0
				},
				// 选择地区
				cityshow: false,
				selectArea: '',
				// 数据汇总
				tableData: [],
				originalTableData:{},
				key: '',
				// 时间类型
				timeType: 0, //筛选时间类别：0全部，1今日，2昨日，3本月，4上月，5本季度，6上季度，7本年，9自定义时间段
				startDate: '', //开始时间
				endDate: '', //结束时间
				timeName: '全部',
				// 修改名称
				editDialogVisible: false,
				editname: ''
			}
		},
		onLoad(option) {
			console.log('option',option)
			this.id = option.id
			this.getDetails()
			this.getSumByEnterprise()
		},
		methods: {
			getDetails(){
				this.loading = true
				this.$u.get('/Enterprise/Detail?id=' + this.id).then((res) => {
					this.details = res
				}).catch(() => {
					
				}).finally(()=>{
					this.loading = false
				})
			},
			// 更换模式
			changeMode() {
				let type, msg, title
				if (this.details.financemode == '帐户分管') {
					type = 1
					msg = '账户统管模式为，各部门回收余额统一到客户组内，授权给一个部门进行管理'
					title = '是否切换成“账户统管”?'
				} else {
					type = 0
					msg = '账户分管模式为，各部门回收余额分给各部门管理'
					title = '是否切换成“账户分管”?'
				}
				uni.showModal({
					title: title,
					content: msg,
					success: (res)=> {
						if (res.confirm) {
							this.ChangeSettlementType(type)
						} else if (res.cancel) {
						
						}
					}
				})
			},
			// 切换账户管理模式
			ChangeSettlementType(type) {
				this.$u.post('/Enterprise/ChangeFinanceMode', {
					"Id": this.details.id,
					"FinanceMode": type
				}).then(() => {
					uni.showToast({
						title: '更换成功'
					})
					this.getDetails()
				})
			},
			// 指定用户
			confirmStaff(item) {
				console.log(item)
				this.addForm.name = item.name
				this.addForm.staffId = item.id
			},
			// 绑定客户组
			binding(){
				this.showWindow = true
			},
			//绑定用户
			bindUser(obj) { 
				this.$u.post('/Enterprise/Bind', {
					userId: obj.id,
					id: this.id
				}).then((res) => {
					// this.$message.success(res.msg);
					uni.showToast({
						title: '绑定成功'
					})
					this.getDetails()
				})
			},
			//解绑客户组
			unbinding() {
				uni.showModal({
					title: '提示',
					content: '您确定要解绑客户组吗?',
					success: (res)=> {
						if (res.confirm) {
							this.$u.post('/Enterprise/UnBind',[this.id]).then((res) => {
								uni.showToast({
									title: '操作成功'
								})
								this.getDetails()
								// this.getOrderRecord(this.id)
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			getSelectCity(arr) { //城市选择回调函数
				console.log(arr)
				this.cityshow = false
				// this.selectArea = '';
				let cityidArr = [];
				let getArr = arr.filter(n => n.id != 0)
				let areaname = '';
				getArr.forEach((item, index) => {
					if (index == getArr.length - 1) {
						areaname += item.name
					} else {
						areaname += item.name + '-'
					}
					cityidArr.push(item.id);
				});
				// if (cityidArr.length > 0)
				// 	// this.form.cityid = cityidArr.join(',');
				// 	this.form.cityid = cityidArr[cityidArr.length - 1];
				// if (areaname)
				// 	this.selectArea = areaname;
					
				let cityId = cityidArr[cityidArr.length - 1]
				this.$u.post('/Enterprise/Edit', {
					id: this.id,
					name: this.details.name,
					cityId: cityId,
				}).then((res) => {
					uni.showToast({
						title: '修改地区成功'
					})
					this.getDetails()
				})
			},
			// 回收汇总
			getSumByEnterprise() {
				this.tableData = []

				this.$u.post(`/User/Order/SumByType`, {
					enterpriseId: this.id,
					timeType: this.timeType,
					startDate: this.startDate,
					endDate: this.endDate,
					orderType: null, //订单类型：null全部，1.线上单，2.线下单
					userType: 1, //用户类型：0全部，1客户组订单，2用户订单
					includeDepartment: this.details.parentid > 0?false:true, //是否包含下级部门(EnterpriseId>0时有效)
				}).then(res => {
					this.tableData = this.flattenData(res.type)
					this.originalTableData = res
					console.log(this.tableData)
					this.loading = false
				})
			},
			// 递归数据处理
			flattenData(data, level = 0, parentPath = []) {
				let result = [];
				data.forEach(item => {
					const currentPath = [...parentPath, item];
					item.product.forEach(product => {
						result.push({
							id: product.id,
							name: product.name,
							isweighing: product.isweighing,
							weight: product.weight,
							amount: product.amount,
							large: item.name,
							bigid: item.id,
							level: level,
							isCategory: true,
						});
					})
					// 递归处理子类型
					if (item.type && item.type.length > 0) {
						// console.log(currentPath)
						const childData = this.flattenData(item.type, level + 1, currentPath);
						console.log('递归处理子类型-childData:', childData)
						childData.forEach((cell) => {
							result = result.concat([{
								id: cell.id,
								name: `${cell.large}-${cell.name}`,
								// name: this.getSubCategoryName(currentPath),
								isweighing: cell.isweighing,
								weight: cell.weight,
								amount: cell.amount,
								large: currentPath[0].name,
								bigid: currentPath[0].id,
								level: cell.level,
								isCategory: cell.isCategory,
							}]);
						})
				
					}
				})
				return result;
			},
			searchKeyword(key){
				this.tableData = this.originalTableData.type.filter((item)=>item.name.includes(key) || item.large.includes(key))
			},
			filterChange(obj){
				console.log('filterChange',obj)
				for(let key in obj){
					this.$set(this,key,obj[key])
				}
				switch (this.timeType){
					case 0:
						this.timeName='全部'
						break;
					case 1:
						this.timeName='今日'
						break;
					case 2:
						this.timeName='昨日'
						break;
					case 3:
						this.timeName='本月'
						break;
					case 4:
						this.timeName='上月'
						break;
					case 5:
						this.timeName='本季度'
						break;
					case 6:
						this.timeName='本年'
						break;
					case 7:
						this.timeName='本年'
						break;
					case 8:
						this.timeName='上年'
						break;
					default:
						this.timeName=`${this.startDate} 至 ${this.endDate}`
						break;
				}
				this.getSumByEnterprise();
			},
			// 修改名称
			edit(){
				if(this.details.parentid == 0){
					this.editname = this.details.name;
				}else{
					this.editname = this.details.department;
				}
				this.editDialogVisible = true
			},
			confirmEditName() { 
				this.$u.post('/Enterprise/Edit', {
					id: this.id,
					name: this.editname,
					cityId: 0,
				}).then((res) => {
					uni.showToast({
						title:'修改名称成功'
					})
					this.getDetails()
					this.editDialogVisible = false
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.grid-box{
		margin: 0;
		border-radius: 0;
	}
	.middle {
		background-color: #fff;
		font-size: 24rpx;
		line-height: 40rpx;
		text-align: center;
		.item{
			flex: 1;
		}
		.label{
			
		}
		.unit{
			font-size: 24rpx;
			// color: $u-tips-color;
		}
	}
	.links{
		color: $u-color-blue;
		border-bottom: 1px solid $u-color-blue;
	}
	.table-list{
		background-color: #fff;
		padding: 0 20rpx;
		.tr{
			display: flex;
			align-items: center;
			&:active{
				opacity: 0.6;
			}
			.th{
				flex: 1;
				color: $u-tips-color;
				font-size: 24rpx;
				line-height: 3em;
			}
			.td{
				flex: 1;
				padding: 24rpx 0;
			}
		}
		.links{
			color: $u-color-blue;
			border-bottom: 1px solid $u-color-blue;
		}
		.divider{
			border-right: 1px solid $u-border-color;
			height: 14px;
			padding-left: 8px;
			margin-right: 8px;
		}
	}
</style>
